import { getGroupList } from '@/apis/accessManagement/group'
import { muteGroup } from '@/apis/accessManagement/group'
import { cancelMuteGroup } from '@/apis/accessManagement/group'
import { dismissGroup } from '@/apis/accessManagement/group'
import ExcelTable from '@/components/exportExcel'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import {Button, Drawer, Modal, Form, Input, Flex, Tree,message,Spin} from 'antd'
import {useRef, useState,useEffect} from 'react'
import {useNavigate} from 'react-router-dom'
import dayjs from 'dayjs'

const GroupList: React.FC = () => {
    useRef<ActionType>()
    useRef<ProFormInstance>()
    const navigate = useNavigate()
    const actionRef = useRef();
    const [loading, setLoading] = useState(false);
    const [messageApi, contextHolder] = message.useMessage()
    const [tableItem, setTableItem] = useState()
    const [form] = Form.useForm()
    const [restPwd, setResetPwdDrawer] = useState(false)
    const [addGroupAuth, setAddGroupAuth] = useState(false)
    const [editGroupAuth, setEditGroupAuth] = useState(false)
    const [checkGroupAuth, setCheckGroupAuth] = useState(false)
    const [muteAllAuth, setMuteAllAuth] = useState(false)
    const [dismissGroupAuth, setDismissGroupAuth] = useState(false)

    function showResetPwdDrawer(item: any) {
        setTableItem(item)
        setResetPwdDrawer(true)
    }

    function subNewPwd() {
        form.resetFields()
        setResetPwdDrawer(false)
    }

    function checkMuteStatus(record:any) {
        record.groupInfo.status === 3?subCancelMuteGroup(record):subMuteGroup(record)
    }

    // 全体禁言
    const subMuteGroup = async (params:any) => {
        setLoading(true)
        try {
            const response = await muteGroup({
                groupID: params.groupInfo.groupID,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('全体禁言成功');
                    actionRef.current?.reload()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 取消全体禁言
    const subCancelMuteGroup = async (params:any) => {
        setLoading(true)
        try {
            const response = await cancelMuteGroup({
                groupID: params.groupInfo.groupID,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('取消全体禁言成功');
                    actionRef.current?.reload()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 解散群组
    const subdismissGroup = async (params:any) => {
        setLoading(true)
        try {
            const response = await dismissGroup({
                groupID: params.groupInfo.groupID,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('解散群组成功');
                    actionRef.current?.reloadAndRest()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        const processAuthData = (authData: any[]) => {
            // 递归
            const traverse = (nodes: any[]) => {
                for (const node of nodes) {
                    if (node.name === '群组' && node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                    // 检查子节点的 name
                    if (node.name === '新增群组') {
                        setAddGroupAuth(true)
                    }
                    if (node.name === '编辑群组') {
                        setEditGroupAuth(true)
                    }
                    if (node.name === '群组成员') {
                        setCheckGroupAuth(true)
                    }
                    if (node.name === '全体禁言') {
                        setMuteAllAuth(true)
                    }
                    if (node.name === '解散群组') {
                        setDismissGroupAuth(true)
                    }
                    // 如果两个权限都已经找到，提前结束递归
                    if (addGroupAuth && editGroupAuth && checkGroupAuth && muteAllAuth && dismissGroupAuth) {
                        return;
                    }
                    // 如果当前节点有子节点，递归处理子节点
                    if (node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                }
            };
            traverse(authData);
            return { addGroupAuth, editGroupAuth,checkGroupAuth,muteAllAuth,dismissGroupAuth};
        };
        const checkRouters = setInterval(() => {
            const authData = window.routers?.routes?.[1]?.children || [];
            if (authData.length > 0) {
                clearInterval(checkRouters); // 停止检查
                processAuthData(authData); // 执行逻辑
            }
        }, 200);
        return () => clearInterval(checkRouters); // 清理定时器
    },[])

    return (
        <>
            {contextHolder}
            <Spin spinning={loading} fullscreen size='large'/>
            <ExcelTable
                actionRef={actionRef}
                requestFn={ params => {
                    // await storeGlobalUser.getUserDetail(); // 确保 userInfo 已加载
                    const { pageNum,pageSize,groupName='',groupID='', ...newParams } = params; // 处理所需参数名
                    const data = getGroupList({
                        ...newParams,
                        pagination: {pageNumber:pageNum,showNumber:pageSize},
                        groupName: groupName,
                        groupID:groupID,
                        // pageSize:pageSize
                    })
                    return data
                }}
                rowSelection={false}
                // toolBarRenderFn={() => [
                //     addGroupAuth && (<Button key="add" onClick={() => {
                //         navigate('/group/groupManage/addGroup?state=1')
                //     }}>新增群组</Button>)
                // ]}
                columns={[
                    {
                        title: '序号',
                        valueType: 'index',
                        hideInSearch: true
                    },
                    {
                        title: '群组ID',
                        dataIndex: 'groupID',
                        render: (_, record) => record.groupInfo?.groupID || '暂无数据',
                    },
                    {
                        title: '群组名称',
                        dataIndex: 'groupName',
                        render: (_, record) => record.groupInfo?.groupName || '暂无数据',
                    },
                    {
                        title: '群主ID',
                        dataIndex: 'ownerUserID',
                        hideInSearch: true,
                        render: (_, record) => record.groupInfo?.ownerUserID || '暂无数据',
                    },
                    // {
                    //     title: '发言状态',
                    //     dataIndex: 'onlineStatus',
                    //     valueType: 'select',
                    //     valueEnum: {
                    //         all: '全部',
                    //         online: '在线',
                    //         offline: '离线'
                    //     }
                    // },
                    {
                        title: '创建人ID',
                        dataIndex: 'creatorUserID',
                        hideInSearch: true,
                        render: (_, record) => record.groupInfo?.creatorUserID || '暂无数据',
                    },
                    {
                        title: '最近登录时间',
                        dataIndex: '',
                        hideInTable: true,
                        hideInSearch: true,
                        valueType: 'dateRange'
                    },
                    {
                        title: '成员数量',
                        dataIndex: 'memberCount',
                        render: (_, record) => record.groupInfo?.memberCount || '暂无数据',
                        hideInSearch: true,
                    },
                    {
                        title: '创建时间',
                        dataIndex: 'createTime',
                        hideInSearch: true,
                        render: (_, record) =>
                            record?.groupInfo?.createTime
                              ? dayjs(record?.groupInfo?.createTime).format('YYYY-MM-DD HH:mm:ss')
                              : '暂无数据',
                    },
                    {
                        title: '验证模式',
                        dataIndex: 'needVerification',
                        hideInSearch: true,
                        render: (_, record) => {
                            if (record?.groupInfo?.needVerification === 1) {
                                return '除群主管理员邀请外，需要验证';
                              }
                              if (record?.groupInfo?.needVerification === 2) {
                                return '直接进群';
                              }
                              return '申请需要同意，邀请直接进群'; // 默认值
                        }
                            // record?.groupInfo?.needVerification
                            //   ? record?.groupInfo?.needVerification
                            //   : '申请需要同意',
                    },
                    {
                        title: '操作',
                        key: 'option',
                        valueType: 'option',
                        render: (_, record) => [
                            editGroupAuth && (<a key="update" onClick={() => {
                                navigate(`/group/groupManage/setGroup?state=2&groupID=${record.groupInfo.groupID}`)
                            }}>修改信息</a>),
                            checkGroupAuth && (
                                <a key="resetPwd" onClick={() => {navigate(`/group/groupManage/groupMember?groupID=${record.groupInfo.groupID}`)}}>群成员</a>
                            ),
                            muteAllAuth && (<a key="disabled" onClick={() => {
                                const forbiddenText = record.groupInfo.status === 3 ? '解除禁言' : '全体禁言'
                                Modal.warning({
                                    title: '提示',
                                    content: `确定${forbiddenText}吗?`,
                                    okText: '确定',
                                    okCancel: true,
                                    onOk() {
                                        checkMuteStatus(record)
                                    }
                                })
                            }}>{record.groupInfo.status === 3 ? '解除禁言' : '全体禁言'}</a>),
                            dismissGroupAuth && (<a key="delete" style={{color: '#FF1616'}} onClick={() => {
                                Modal.warning({
                                    title: '提示',
                                    content: '确定解散群组吗?',
                                    okText: '确定',
                                    okCancel: true,
                                    onOk() {
                                        subdismissGroup(record)
                                    }
                                })
                            }}>解散群组</a>)
                        ]
                    }
                ]}/>

        </>
    )
}

export default GroupList
